import time
import db
import os
import configparser
import json
import requests
from typing import *
 
import os
import json
from pathlib import Path
 
import httpx
from openai import OpenAI

# 读取配置文件  必须重启服务才可以重新加载
config_path = os.path.split(os.path.realpath(__file__))[0]
config = configparser.RawConfigParser()
config.read(config_path+'\config.ini', encoding="utf-8-sig")


class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        super(DecimalEncoder, self).default(o)


class wind():

    def __init__(self):
        # print('__init__')
        # self.dbconn = db.db()

        # print(self.dbconn)
        self.client = OpenAI(
            api_key = "sk-dlwCiNCL54ebpt30BBNe728WBePcBXS9igZDAlwtGYTPIGwi",
            base_url = "https://api.moonshot.cn/v1",
        )
        pass

# ====================================初始化需要配置的参数下==============================

    def send_to_ai_by_file(self,text,file_path):
        # xlnet.pdf 是一个示例文件, 我们支持 pdf, doc 以及图片等格式, 对于图片和 pdf 文件，提供 ocr 相关能力
        file_object = self.client.files.create(file=Path(file_path), purpose="file-extract")
        
        # 获取结果
        # file_content = self.client.files.retrieve_content(file_id=file_object.id)
        # 注意，之前 retrieve_content api 在最新版本标记了 warning, 可以用下面这行代替
        # 如果是旧版本，可以用 retrieve_content
        file_content = self.client.files.content(file_id=file_object.id).text
        
        # print(file_content)
        # exit()
        # 把它放进请求中
        messages = [
            {
                "role": "system",
                "content": "你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。",
            },
            {
                "role": "system",
                "content": file_content,
            },
            {"role": "user", "content": text},
        ]
        
        # 然后调用 chat-completion, 获取 Kimi 的回答
        completion = self.client.chat.completions.create(
            model="moonshot-v1-32k",
            messages=messages,
            temperature=0.3,
        )
        
        print(completion.choices[0].message)
        return completion.choices[0].message.content
    
    
    # 列出ai的文件列表
    def ai_list_file(self):
        file_list = self.client.files.list()
        for file in file_list.data:
            print(file) # 查看每个文件的信息
    
    # 删除ai的文件列表
    def ai_truncate_list_file(self):
        file_list = self.client.files.list()
 
        for file in file_list.data:
            print(file) # 查看每个文件的信息
            print(file.id)        
            self.client.files.delete(file_id=file.id)
    # 发送给AI
    def send_to_ai(self,text):

        print("###系统提示：AI大模型处理中...")
        
        client = OpenAI(
            api_key = "sk-dlwCiNCL54ebpt30BBNe728WBePcBXS9igZDAlwtGYTPIGwi",
            base_url = "https://api.moonshot.cn/v1",
        )
        
        sql_struct = self.get_sql_struct()
        
        messages = [
            {"role": "system", "content": sql_struct},            
            {"role": "system", "content": "你是 星凌AI，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。"},
            {"role": "user", "content": text}
        ]
        # print(messages)
        
        completion = client.chat.completions.create(
            model = "moonshot-v1-8k",
            messages = messages,
            temperature = 0.3,
        )
        
        print("###系统提示：AI大模型处理完毕")
        return completion.choices[0].message.content
    
    
    def get_sql_struct(self):
        
        sql_struct = """
                        /*
            Navicat Premium Data Transfer

            Source Server         : 本地-bdtask
            Source Server Type    : MySQL
            Source Server Version : 80012
            Source Host           : 127.0.0.1:3306
            Source Schema         : bdtask

            Target Server Type    : MySQL
            Target Server Version : 80012
            File Encoding         : 65001

            Date: 20/08/2024 13:53:20
            */

            SET NAMES utf8mb4;
            SET FOREIGN_KEY_CHECKS = 0;

            -- ----------------------------
            -- Table structure for bd_sys_account
            -- ----------------------------
            DROP TABLE IF EXISTS `bd_sys_account`;
            CREATE TABLE `bd_sys_account`  (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '账号',
            `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码',
            `salt` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '盐值',
            `real_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '真实姓名',
            `icon` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '头像',
            `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '邮箱',
            `is_admin` tinyint(4) NULL DEFAULT 0 COMMENT '是否是管理员',
            `mobile` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '手机号',
            `staff_num` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '工号',
            `address` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL,
            `group_id` int(11) NOT NULL COMMENT '分组id',
            `map_id` int(11) NOT NULL COMMENT '映射id',
            `state` tinyint(4) NULL DEFAULT 1 COMMENT '状态',
            `last_login_time` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '最后登录时间',
            `pwd_error_count` int(11) NULL DEFAULT 0 COMMENT '密码错误次数',
            `ip` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '登录ip',
            `ip_detail` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '最后登录地',
            `ding_talk_unique_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '钉钉 用户标识',
            PRIMARY KEY (`id`) USING BTREE,
            UNIQUE INDEX `key_unique_group_map`(`group_id`, `map_id`) USING BTREE,
            UNIQUE INDEX `key_unique_username`(`username`) USING BTREE
            ) ENGINE = InnoDB AUTO_INCREMENT = 117 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '账户表' ROW_FORMAT = Dynamic;

            -- ----------------------------
            -- Table structure for bd_sys_account_dept
            -- ----------------------------
            DROP TABLE IF EXISTS `bd_sys_account_dept`;
            CREATE TABLE `bd_sys_account_dept`  (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `dept_id` int(11) NULL DEFAULT NULL COMMENT '部门id',
            `account_id` int(11) NULL DEFAULT NULL,
            PRIMARY KEY (`id`) USING BTREE,
            UNIQUE INDEX `udx_account_dept_id`(`dept_id`, `account_id`) USING BTREE,
            UNIQUE INDEX `udx_account_id`(`account_id`) USING BTREE
            ) ENGINE = InnoDB AUTO_INCREMENT = 290 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '账户-部门关联表' ROW_FORMAT = Dynamic;

            -- ----------------------------
            -- Table structure for bd_sys_account_menu
            -- ----------------------------
            DROP TABLE IF EXISTS `bd_sys_account_menu`;
            CREATE TABLE `bd_sys_account_menu`  (
            `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户权限表',
            `account_id` int(11) NOT NULL COMMENT '账户id',
            `menu_id` int(11) NOT NULL COMMENT '菜单id',
            PRIMARY KEY (`id`) USING BTREE,
            UNIQUE INDEX `udx_account_id&menu_id`(`account_id`, `menu_id`) USING BTREE
            ) ENGINE = InnoDB AUTO_INCREMENT = 86 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户权限映射表' ROW_FORMAT = Dynamic;

            -- ----------------------------
            -- Table structure for bd_sys_account_role
            -- ----------------------------
            DROP TABLE IF EXISTS `bd_sys_account_role`;
            CREATE TABLE `bd_sys_account_role`  (
            `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户角色绑定表',
            `account_id` int(11) NOT NULL COMMENT '账户id',
            `role_id` int(11) NOT NULL COMMENT '角色id',
            PRIMARY KEY (`id`) USING BTREE,
            UNIQUE INDEX `k_unique`(`account_id`, `role_id`) USING BTREE
            ) ENGINE = InnoDB AUTO_INCREMENT = 298 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户角色映射表' ROW_FORMAT = Dynamic;

            -- ----------------------------
            -- Table structure for bd_sys_dept
            -- ----------------------------
            DROP TABLE IF EXISTS `bd_sys_dept`;
            CREATE TABLE `bd_sys_dept`  (
            `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '部门id',
            `parent_id` int(11) NULL DEFAULT 0 COMMENT '父级部门id',
            `dept_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '部门名称',
            `description` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '描述',
            `sort` int(11) NULL DEFAULT 500 COMMENT '排序',
            `state` tinyint(4) NULL DEFAULT 1 COMMENT '状态',
            `leader_id` int(11) NULL DEFAULT NULL COMMENT '部门领导account_id',
            `leader_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '部门领导姓名',
            `type` tinyint(4) NULL DEFAULT 11 COMMENT '类型 1内置（不允许删除）  11普通',
            `left_tree` int(11) NULL DEFAULT 0 COMMENT '左树',
            `right_tree` int(11) NULL DEFAULT 0 COMMENT '右树',
            `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
            `create_by_ac_id` int(11) NULL DEFAULT NULL COMMENT '创建者id',
            `create_by_ac_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '创建者姓名',
            `update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
            `update_by_ac_id` int(11) NULL DEFAULT NULL COMMENT '修改者id',
            `update_by_ac_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '修改者姓名',
            PRIMARY KEY (`id`) USING BTREE
            ) ENGINE = InnoDB AUTO_INCREMENT = 291 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '部门表' ROW_FORMAT = Dynamic;

            -- ----------------------------
            -- Table structure for bd_sys_menu
            -- ----------------------------
            DROP TABLE IF EXISTS `bd_sys_menu`;
            CREATE TABLE `bd_sys_menu`  (
            `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '节点表',
            `system_id` tinyint(4) NOT NULL DEFAULT 1 COMMENT '系统标识1：业务流程系统 2：CRM ',
            `parent_id` int(11) NULL DEFAULT 0 COMMENT '父节点',
            `type` tinyint(4) NULL DEFAULT NULL COMMENT '类型  1目录  2菜单 3按钮 4外链',
            `title` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '菜单标题',
            `component` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '组件路径',
            `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '组件名称',
            `path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '链接地址',
            `redirect` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '重定向',
            `level` int(11) NULL DEFAULT 0 COMMENT '等级 和depth相同',
            `sort` int(11) NULL DEFAULT 500 COMMENT '排序',
            `icon` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '图标',
            `cache` tinyint(4) NULL DEFAULT 0 COMMENT '缓存 0不缓存  1缓存',
            `hidden` tinyint(4) NULL DEFAULT 0 COMMENT '菜单 隐藏   0展示 1隐藏',
            `state` tinyint(4) NULL DEFAULT 1 COMMENT '节点状态  0禁用  1启用  2仅超管可见   禁用后在分配节点时 就无法查到该节点',
            `is_admin` tinyint(4) NULL DEFAULT 0,
            `left_tree` int(11) NULL DEFAULT NULL COMMENT '左树',
            `right_tree` int(11) NULL DEFAULT NULL COMMENT '右树',
            `method` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '方式 例如get post 等',
            `permission` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '权限',
            `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
            `create_by_ac_id` int(11) NULL DEFAULT NULL COMMENT '创建者id',
            `create_by_ac_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建者姓名',
            `update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
            `update_by_ac_id` int(11) NULL DEFAULT NULL COMMENT '修改者id',
            `update_by_ac_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改者姓名',
            PRIMARY KEY (`id`) USING BTREE
            ) ENGINE = InnoDB AUTO_INCREMENT = 140 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '菜单权限表' ROW_FORMAT = Dynamic;

            -- ----------------------------
            -- Table structure for bd_sys_role
            -- ----------------------------
            DROP TABLE IF EXISTS `bd_sys_role`;
            CREATE TABLE `bd_sys_role`  (
            `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '角色表',
            `role_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '角色名称',
            `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '描述',
            `state` tinyint(4) NULL DEFAULT NULL COMMENT '状态',
            `sort` int(11) NULL DEFAULT 5000 COMMENT '排序',
            `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间 ',
            `create_by_ac_id` int(11) NULL DEFAULT NULL COMMENT '创建者id',
            `create_by_ac_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建者姓名',
            `update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
            `update_by_ac_id` int(11) NULL DEFAULT NULL COMMENT '修改者id',
            `update_by_ac_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改者姓名',
            PRIMARY KEY (`id`) USING BTREE
            ) ENGINE = InnoDB AUTO_INCREMENT = 15 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '角色表' ROW_FORMAT = Dynamic;

            -- ----------------------------
            -- Table structure for bd_sys_role_menu
            -- ----------------------------
            DROP TABLE IF EXISTS `bd_sys_role_menu`;
            CREATE TABLE `bd_sys_role_menu`  (
            `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '菜单（权限）角色绑定表',
            `role_id` int(11) NOT NULL,
            `menu_id` int(11) NOT NULL,
            PRIMARY KEY (`id`) USING BTREE,
            UNIQUE INDEX `k_unique`(`role_id`, `menu_id`) USING BTREE
            ) ENGINE = InnoDB AUTO_INCREMENT = 4542 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '角色权限表' ROW_FORMAT = Dynamic;

            -- ----------------------------
            -- Table structure for bd_sys_setting
            -- ----------------------------
            DROP TABLE IF EXISTS `bd_sys_setting`;
            CREATE TABLE `bd_sys_setting`  (
            `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '系统参数表',
            `param_key` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '参数名',
            `param_value` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '参数值',
            `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '描述',
            `sort` int(11) NULL DEFAULT 5000 COMMENT '排序',
            `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
            `create_by_ac_id` int(11) NULL DEFAULT NULL COMMENT '创建者id',
            `create_by_ac_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建者姓名',
            `update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
            `update_by_ac_id` int(11) NULL DEFAULT NULL COMMENT '修改者id',
            `update_by_ac_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改者姓名',
            PRIMARY KEY (`id`) USING BTREE,
            INDEX `idx_param_key`(`param_key`) USING BTREE
            ) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '系统设置表' ROW_FORMAT = Dynamic;

            -- ----------------------------
            -- Table structure for bd_sys_user
            -- ----------------------------
            DROP TABLE IF EXISTS `bd_sys_user`;
            CREATE TABLE `bd_sys_user`  (
            `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
            `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '账号',
            `real_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '姓名',
            `profession_id` int(11) NULL DEFAULT NULL COMMENT '岗位id',
            `level` tinyint(4) NULL DEFAULT NULL COMMENT '等级   类似阿里等级制度',
            `join_time` date NULL DEFAULT NULL COMMENT '工作信息  入职时间',
            `position_id` int(11) NULL DEFAULT NULL COMMENT '工作信息  职位id  如总监等',
            `workplace` varchar(125) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '工作地点',
            `seat` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '工作信息  工位',
            `sex` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '个人信息  性别  ',
            `birthday` date NULL DEFAULT NULL COMMENT '个人信息  生日',
            `identity_card` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '个人信息  身份证',
            `graduation_school` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '个人信息  毕业学校',
            `graduation_time` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '个人信息  毕业时间',
            `graduation_professional` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '个人信息  毕业专业',
            `dimission_reason` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT '离职原因',
            `dimission_time` date NULL DEFAULT NULL COMMENT '离职日期',
            `add_type` tinyint(4) NULL DEFAULT 1 COMMENT '添加方式   1用户自主注册  2后台添加',
            `remark` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT '备注',
            `role_name` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT '归属的角色名 多个用英文逗号分隔',
            `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
            `create_by_ac_id` int(11) NULL DEFAULT NULL COMMENT '创建者id',
            `create_by_ac_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '创建者姓名',
            `update_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
            `update_by_ac_id` int(11) NULL DEFAULT NULL COMMENT '修改者id',
            `update_by_ac_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '修改者姓名',
            PRIMARY KEY (`id`) USING BTREE
            ) ENGINE = InnoDB AUTO_INCREMENT = 117 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '用户表' ROW_FORMAT = Dynamic;

            SET FOREIGN_KEY_CHECKS = 1;

        """
        
        return sql_struct
    

    #读取全部的配置信息
    def allConfig(self):
        return config

    #通常用来判断当前是否为跑服务的时间 传入开始和结束时间  如果是工作日  且当前时间在开始和结束时间当中 则返回true 否则返回false
    #@param 传入的时间格式 xx:xx:xx
    #@ runtype  服务跑的类型  1仅在交易日跑  2每天都跑
    def runTime(self,start='09:20:00',end='15:35:00',runtype = 1):
        try:
            flag = False

            now = time.strftime("%Y-%m-%d %H:%M:%S")
            # 0为日期  1为时间  ['2019-05-27', '17:51:15']
            nowArr = now.split(' ')

            resTran = 1


            if nowArr[1] >= start and nowArr[1] <= end and resTran >0:
                flag = True

            return flag
        except Exception as e:
            self.logAbnormal(0, 'wind', 'wind', e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)

    # 异常日志
    def logAbnormal(self, type, server_display_name, server_description, file, line, remark=None):
        try:
            file = file.replace('\\','/')

            if remark is not None:
                tmp_remark = str(remark)
                tmp_remark = tmp_remark.replace("'",' ')
                tmp_remark = tmp_remark.replace('"',' ')

            sql = 'insert into tb_log_server_abnormal(`type`,server_display_name,server_description,file,line,remark) ' \
                  'values({},"{}","{}","{}",{},"{}")'.format(type, server_display_name, server_description, file, line,
                                                             tmp_remark)

            print(sql)
            self.dbconn.opt_one(sql)
        except Exception as e:
            print('无法写入异常日志，：{}',e)
            pass



    # 运行日志
    def logRun(self, type, server_display_name, server_description, remark=None):
        try:

            sql = 'insert into tb_log_server_run(`type`,server_display_name,server_description,remark) ' \
                  'values({},"{}","{}","{}")'.format(type, server_display_name, server_description, remark)
            self.dbconn.opt_one(sql)

        except Exception as e:
            self.logAbnormal(0, 'wind', 'wind', e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)


    # 实用日志
    def logPractical(self, type, server_display_name, server_description, remark=None,return_content=None):
        try:

            sql = "insert into tb_log_server_practical(`type`,server_display_name,server_description,remark,return_content) " \
                  "values({},'{}','{}','{}','{}')".format(type, server_display_name, server_description, remark,return_content)

            self.dbconn.opt_one(sql)

        except Exception as e:
            self.logAbnormal(0, 'wind', 'wind', e.__traceback__.tb_frame.f_globals["__file__"], e.__traceback__.tb_lineno, e)


    # 发送数据到远程接口
    def remoteApi(self, arr ,url):

        try:

            post_arr = {
                'param': arr
            }

            # # json后的数据
            # json_data = json.dumps(post_arr, cls=DecimalEncoder, separators=(',', ':'))
            #
            # # 加密后的数据
            # encrypt_data = obj_aes.encrypt(json_data)

            # 插入发送日志
            # sql = """insert into tb_log_api(`serial`,send_receive,content_encrypt,content_decrypt,time_create,scene)
            #       values('{}','{}','{}','{}','{}','{}')
            #       """.format(serial, 1, encrypt_data, json_data, time_now, scene)
            #
            # lastid = self.dbconn.opt_one(sql)['data']

            # 发送到远程端口
            headers = {'Content-Type': 'application/json'}
            response = requests.post(url=config['remote_config']['device_url'] + url,
                                     headers=headers, data=post_arr)

            response_content = response.content.decode('utf-8')

            print(response_content)

            # return response_decrypt
        except Exception as e:
            self.logAbnormal(0, 'wind', 'wind', e.__traceback__.tb_frame.f_globals["__file__"],
                             e.__traceback__.tb_lineno, e)




    #手动关闭数据库连接
    def dbclose(self):

        self.dbconn.dbclose()
